﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using DbSharp.Utils.IO;
using DbSharp.Framework.Storage.Export;


namespace DbSharp.Tools.Xml2Excel
{
    class Program
    {
        static bool TryParseArguments(string[] args, out string xmlFile, out string excelFile)
        {
            xmlFile = string.Empty;
            excelFile = string.Empty;
            if (args == null)
                return false;
            else if (args.Length < 2)
                return false;
            else
            {
                xmlFile = args[0];
                excelFile = args[1];
                return File.Exists(xmlFile);
            }
        }

        static void Export(string xmlFile, string excelFile)
        {
            var xDoc = XDocument.Load(xmlFile);
            XElement scalarDataElement = xDoc.Root.Element("resultsetData");

            ExcelExportWriter exporter = new ExcelExportWriter();
            if (scalarDataElement != null)
                exporter.Export(excelFile, scalarDataElement, long.MaxValue);
            else
                exporter.Export(excelFile, xDoc.Root.Elements("row"), long.MaxValue);
        }


        static string GetUsageInfo()
        {
            string fmt = @"

Description:
  Convert xml file that generated by this suite to Excel format. 
  After conversion, the Excel file can be used for future data comparison.

Hint: Due to Excel 2003 and earlier version constraints: 
 1. In xml file, length of xml node value cannot be greater than 255 characters.
 2. In xml file, row node count cannot be greater than 65535. 
 3. After conversion, please remove the first row manually before the Excel file will be used for future data comparison. 

Usage:
  {0} XmlFileName ExcelFileName ";

            string info = string.Format(fmt, PathHelper.GetAppFileNameWithoutPath());
            return info;
        }

        static void Main(string[] args)
        {
            string xmlFile;
            string excelFile;
            bool validArgs = TryParseArguments(args, out xmlFile, out excelFile);
            if (validArgs == false)
            {
                Console.Write(GetUsageInfo());
                Console.WriteLine();
            }
            else
            {
                try
                {
                    Export(xmlFile, excelFile);
                    string fmt = "{0} conversion completed, output file is {1}.";
                    Console.WriteLine(string.Format(fmt, xmlFile, excelFile));
                    Console.WriteLine();
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                    Console.WriteLine();
                }
            }
        }
    }
}
